<template>
  <el-drawer :visible.sync="drawer" direction="rtl" size="50%" :with-header="false" :width="700"
    :destroy-on-close="true">
    <div class="drawer_box">
      <div class="drawer_title">
        <div class="drawer_t">
          <div class="drawer_t_l">
            <img class="drawer_t_l_img" src="/static/skin/herodoo/main/platform/home/img/piliangoumai.png" alt="" />
            编辑退款申请
          </div>
          <img class="drawer_t_r" src="/static/skin/herodoo/main/platform/home/img/guanbi.png" alt=""
            @click="drawer = false" />
        </div>
      </div>
      <div class="drawer_content">
        <div class="content-box">
          <div class="label">权益名称:</div>
          <div class="desc name" @click="drawerUpDetail">
            {{ messageList.Name || messageList.NAME }}
          </div>
        </div>
        <div class="content-box">
          <div class="label">购买数量:</div>
          <div class="desc">{{ messageList.Quantity }}</div>
        </div>

        <div class="content-box">
          <div class="label">购买金额(元):</div>
          <div class="desc">{{ messageList.UserPayTotalPrice }}</div>
        </div>

        <div class="content-box">
          <div class="label">下单时间:</div>
          <div class="desc">{{ messageList.CreateTime }}</div>
        </div>

        <!-- <div class="content-box">
          <div class="label">申请退款时间:</div>
          <div class="desc">{{ messageList.RefundTime }}</div>
        </div> -->
        <div class="content-box">
          <div class="label">申请退款数量:</div>
          <div class="desc">
            <el-input-number v-model="form.num" @change="handleChange" :min="1" :max="messageList.Quantity"
              label="请填写申请退货数"></el-input-number>
          </div>
        </div>
        <div class="content-box" v-if="objInfo">
          <div class="label">手续费(元):</div>
          <div class="desc">
            {{ serverCharge }}
          </div>
        </div>
        <div class="content-box" v-if="objInfo">
          <div class="label">手续费%:</div>
          <div class="desc">{{ objInfo.ServiceCharge * 100 }}%</div>
        </div>
        <div class="content-box" v-if="objInfo">
          <div class="label">应退金额(元):</div>
          <div class="desc">
            {{
              (messageList.CostPrice * 100 * form.num - serverCharge * 100) /
              100
            }}元
          </div>
        </div>
        <div class="content-box">
          <div class="label">申请退款金额(元):</div>
          <div class="desc">
            <el-input v-model="form.price" placeholder="请输入申请退款金额"></el-input>
            <span class="more" v-if="objInfo">最多可退{{
              (messageList.CostPrice * 100 * form.num - serverCharge * 100) /
              100
            }}</span>
          </div>
        </div>
        <div class="content-box">
          <div class="label">请选择售后原因:</div>
          <div class="desc radio">
            <el-radio-group v-model="form.radio" @change="changeRadio">
              <el-radio label="1">计划有变，无法按时使用</el-radio>
              <el-radio label="2">多拍/拍错/不想要</el-radio>
              <el-radio label="3">位置/时间不满意</el-radio>
              <el-radio label="4">其他</el-radio>
            </el-radio-group>
            <el-input v-if="form.radio == 4" v-model="form.reson" placeholder="请输入其他原因"></el-input>
          </div>
        </div>
      </div>

      <div class="drawer_footer">
        <div class="footer-btn" @click="save">确认</div>
      </div>
    </div>
  </el-drawer>
</template>

<script>
export default {
  props: {
    messageList: {
      type: Object,
      default: {}
    }
  },
  data() {
    return {
      octopus: this.$parent.$parent.octopus,
      drawer: false,
      form: {
        num: 1,
        radio: "1",
        price: "0",
        reson: ""
      },
      all: 0,
      objInfo: null,
      id: '',
    };
  },
  computed: {
    serverCharge() {
      let num = this.objInfo.ServiceCharge * this.messageList.CostPrice;
      return Math.ceil(num * 100) / 100;
    }
  },
  watch: {
    messageList: {
      handler(v, e) {
      }
    }
  },
  created() {
  },
  methods: {
    drawerOp(id) {
      this.drawer = true;
      this.id = id;
      this.form.radio = '1';
      this.form.reson = ''
      // this.getInfo();
      this.prePefund();
    },
    changeRadio(e) {
      this.$forceUpdate();
    },
    drawerUpDetail() {
    },
    getInfo() {
      this.octopus.request.api.post(
        "/Octopus/Engine/List",
        {
          id: 1241, // 菜单表的八爪鱼ID
          cellData: [
            { name: "CompanyID" }, // 公司ID
            { name: "CreateTime" }, // 创建时间
            { name: "CreateUserID" }, // 创建人
            { name: "EquityID" }, // 权益ID
            { name: "EquityName" }, // 权益名称
            { name: "ID" }, // ID
            { name: "InventoryID" }, // 库存
            { name: "Name" }, // 规则名称
            { name: "ProductID" }, // 产品
            { name: "ServiceCharge" }, // 手续费（%）
            { name: "Status" }, // 是否启用
            { name: "TimeLimit" }, // 时限（默认小时）
            { name: "TypeID" }, // 规则类型（1小时  2天）
            { name: "UpdateTime" } // 修改时间
          ],
          paramData: {
            EquityID: this.messageList.ID
          }
        },
        // 处理回调事件，通过分析data.status.code的状态来实现。
        data => {
          if (data.status.code === 200) {
            if (data.content.queryData.length > 0) {
              let time = new Date();
              let timeCreate = new Date(this.messageList.ExpireTime);
              let hours = Math.abs(timeCreate - time) / (1000 * 60 * 60);
              let status;
              for (let rule of data.content.queryData) {
                if (hours <= rule.TimeLimit) {
                  status = rule;
                  break;
                }
              }
              this.all = status
                ? (this.messageList.UserPayTotalPrice -
                  this.messageList.ServiceCharge) *
                (status.ServiceCharge / 100)
                : this.messageList.UserPayTotalPrice;
            }
          } else {
            this.octopus.tips.error(data);
          }
        }
      );
    },
    getTime(start, end) {
      let timestamp = Date.parse(new Date()) / 1000; //计算当前时间戳 (毫秒级)
      let dateBegin = new Date(start).getTime();
      let dateEnd = new Date(end).getTime();
      let date1 = dateBegin;
      let date2 = dateEnd; //结束时间
      let date3 = (date2 - date1) * 1000; //时间差的毫秒数
      //计算出相差天数
      let days = Math.floor(date3 / (24 * 3600 * 1000 * 1000));
      //计算出小时数
      let leave1 = date3 % (24 * 3600 * 1000 * 1000); //计算天数后剩余的毫秒数
      let hours = Math.floor(leave1 / (60 * 60 * 1000 * 1000));
      //计算相差分钟数
      let leave2 = leave1 % (60 * 60 * 1000 * 1000); //计算小时数后剩余的毫秒数
      let minutes = Math.floor(leave2 / (60 * 1000 * 1000));
      //计算相差秒数
      let leave3 = leave2 % (60 * 1000 * 1000); //计算分钟数后剩余的毫秒数
      let seconds = Math.round(leave3 / (1000 * 1000));

      let times = {
        title: `${days}天 ${hours}小时${minutes}分钟${seconds}秒"`,
        arr: [days, hours, minutes, seconds]
      };
      // return   days + "天 " + hours + "小时 " + minutes + " 分钟" + seconds + " 秒"
      return times;
    },
    save() {
      if (this.form.radio < 4) {
        this.form.reson = [
          "计划有变，无法按时使用",
          "多拍/拍错/不想要",
          "位置/时间不满意"
        ][this.form.radio - 1];
      }
      if (
        this.form.price >
        (this.messageList.CostPrice * 100 * this.form.num -
          this.serverCharge * 100) /
        100
      ) {
        this.octopus.tips.error("退款金额不能大于最多可退金额！");
        return;
      }

      this.$confirm("是否发起退款申请?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(res => {
        if (res == "confirm") {
          this.pefundApply();
        }
      });
    },
    api_1203(data) {
      this.octopus.request.api.post(
        "/Octopus/Engine/Item",
        {
          id: 1203, // 菜单表的八爪鱼ID
          type: "CREATE",
          // value: this.messageList.ID,
          cellData: [
            { name: "OutRefundCode", defaultValue: data.OutRefundCode }, // 退款订单号
            { name: "PayCode", defaultValue: data.TradeCode }, // 订单的ID
            { name: "PurchaseID", defaultValue: this.messageList.ID }, // 订单的ID
            { name: "PlatformID", defaultValue: this.messageList.PlatformID }, // 退款平台（1PC 2小程序  3H5）
            { name: "EquityID", defaultValue: data.EquityID }, // 权益ID
            { name: "Quantity", defaultValue: this.form.num }, // 退款数量
            { name: "RefundAmount", defaultValue: this.form.price }, // 退款数量
            { name: "RefundReasons", defaultValue: this.form.reson }, // 退款原因
            {
              name: "UpdateTime",
              defaultValue:
                new Date().toJSON().substring(0, 10) +
                " " +
                new Date().toTimeString().substring(0, 8)
            }
          ],
          paramData: {}
        },
        // 处理回调事件，通过分析data.status.code的状态来实现。
        data => {
          if (data.status.code === 200) {
            this.api_1218();
          } else {
            this.octopus.tips.error(data);
          }
        }
      );
    },
    api_1218() {
      this.octopus.request.api.post(
        "/Octopus/Engine/Item",
        {
          id: 1218, // 菜单表的八爪鱼ID
          type: "CREATE",
          cellData: [
            {
              name: "CreateTime",
              defaultValue:
                new Date().toJSON().substring(0, 10) +
                " " +
                new Date().toTimeString().substring(0, 8)
            }, // 时间
            { name: "RefundID", defaultValue: this.messageList.ID }, // 退款表ID
            { name: "CreateUserID", defaultValue: this.octopus.passport.id }, // 退款人
            { name: "Status", defaultValue: 2 }
          ],
          paramData: {}
        },
        // 处理回调事件，通过分析data.status.code的状态来实现。
        data => {
          if (data.status.code === 200) {
            // this.pefundApply();
            this.octopus.tips.success("发起退货申请成功，请等待审批。");
            this.drawer = false;
            this.$emit("reload");
          } else {
            this.octopus.tips.error(data);
          }
        }
      );
    },
    // 申请退款
    pefundApply() {
      this.octopus.tools.openAPI(
        "/ESB/AIGC/Refund/PC/CreateRefund",
        {
          PurchaseID: this.id, // 订单ID
          UserID: this.octopus.passport.id, // 退款发起人ID
          PayCode: this.messageList.Code, //交易订单ID
          PlatformID: this.messageList.PlatformID, // 平台ID
          RefundReasons: this.form.reson, // 退款原因
          EquityID: this.messageList.EquityID, // 订单表中的权益
          Quantity: this.form.num, // 选择退款的数量（未使用）
          MerchantID: this.messageList.MerchantID, // 买家
          CompanyID: this.messageList.CompanyID, // 卖家
          RefundAmount: this.form.price,//输入金额
        },
        datas => {
          if (datas.content.status.code == 200) {
            // this.api_1203(data.content.content);
            this.octopus.tips.success("发起退款申请成功，请等待审批。");
            // 发送消息 传值说明 模版ID ，消息类型 ，消息里的字段 ，创建用户ID，接收公司ID，接收群组ID
            // 
            // 获取用户组
            this.$utils.getGroupInfo(this, '超级管理员,高级管理员,业务管理员',1).then((res) => {
              console.log('发送消息的用户组：', res);
              // 发送消息 传值说明 模版ID ，消息类型 ，消息里的字段 ，创建用户ID，接收公司ID，接收群组ID
              res.length > 0 && this.$utils.sendMessageMulti(8,2,{PurchaserName:this.messageList.MerchantIDName,EquityName:this.messageList.Name},this.octopus.passport.id,1,res,this);
              
            });
            this.drawer = false;
            this.$emit("reload");

          } else {
            this.octopus.tips.error(datas.content.status.message);
          }
        }
      );
    },
    // 获取退款信息
    prePefund() {
      this.octopus.tools.openAPI(
        "/ESB/AIGC/Refund/PC/RefundRate",
        {
          EquityID: this.messageList.EquityID
        },
        datas => {
          if (datas.content.status.code == 200) {
            try {
              this.objInfo = JSON.parse(datas.content.content);
            } catch (e) {

            }
          } else {
            this.octopus.tips.error(datas.content.status.message);

            setTimeout(() => {
              this.drawer = false
            }, 500);
          }
        }
      );
    },
    getServerCharge(num) {
      return Math.ceil(num * 100) / 100;
    }
  }
};
</script>

<style scoped>
.drawer_box {
  height: calc(100% - 5rem);
  display: flex;
  flex-direction: column;
}

.drawer_title {
  box-shadow: 0px 5px 5px rgb(230 228 228 / 30%);
  padding: 1rem 0;
}

.title {
  font-size: 1.8rem;
  font-weight: bold;
  padding: 1rem 0;
}

.drawer_t {
  padding: 0 2.8rem;
  display: flex;
  justify-content: space-between;
}

.drawer_t_l {
  display: flex;
  align-items: center;
  font-size: 2rem;
  font-weight: bold;
}

.drawer_t_l_img {
  width: 2.8rem;
  margin-right: 1rem;
}

.drawer_t_r {
  width: 3rem;
  height: 3rem;
  cursor: pointer;
}

.list-box {
  display: flex;
  width: 100%;
  justify-content: space-between;
}

.list-box {
  /* height: 3.5rem; */
  line-height: 4rem;
  margin-top: 2rem;
}

.list-box .left {
  width: 20%;
  font-size: 1.5rem;
  /* display: flex;
      align-items: center; */
}

.list-box .right {
  width: 80%;
}

.list-box .right .delte {
  font-size: 1.6rem;
  color: #898582;
  margin-left: 2rem;
  cursor: pointer;
}

.list-box .right .delte:hover {
  color: #f87338;
}

.list-box .right .add_content {
  height: 4.5rem;
  line-height: 4.5rem;
  border: 1px dashed #f87338;
  display: inline-block;
  padding: 0 1.5rem;
  cursor: pointer;
  border-radius: 0.5rem;
}

.list-box .right .el-input {
  width: 100%;
  height: 4.5rem;
}

.list-box .right .add_content i {
  color: #f87338;
  font-weight: 700;
  margin-right: 0.5rem;
}

.drawer_content {
  overflow-y: auto;
  margin-top: 1.5rem;
  height: calc(100vh - 13rem);
  padding: 0 3rem;
  width: 100%;
  padding-bottom: 1rem;
}

.drawer_content .title {
  font-size: 1.8rem;
  font-weight: bold;
}

.drawer_content .title2 {
  font-size: 1.8rem;
}

.drawer_content .driver-title {
  margin-top: 1em;
}

.drawer_footer {
  display: flex;
  justify-content: flex-end;
  align-content: center;
}

.drawer_footer .footer-btn {
  line-height: 4rem;
  background-color: #f78c51;
  color: #fff;
  margin: 0 1rem;
  padding: 0 3rem;
  border-radius: 0.5rem;
  cursor: pointer;
}

.drawer_footer .reject {
  background-color: #2e3037;
}

.content-box {
  display: flex;
  align-items: center;
  margin: 2rem 0 2rem 2em;
}

.mt-10 {
  margin-top: 20px;
}

.content-box .label {
  width: 25%;
}

.content-box .label .label-bold {
  font-size: 1.8rem;
  font-weight: bold;
}

.content-box .desc {
  /* flex: 1; */
  display: flex;
  flex-direction: row;
  align-items: center;
}

.content-box .radio {
  display: flex;
  flex-direction: column;
}

.radio>>>.el-radio-group {
  display: flex;
  flex-direction: column;
}

.radio>>>.el-radio {
  margin: 5px 0;
}

.desc {
  position: relative;
  width: 75%;
  align-items: flex-start;
}

.desc.radio {
  align-items: flex-start;
}

.more {
  position: absolute;
  top: 50%;
  right: 10px;
  transform: translate(0, -50%);
  color: #ff9132;
}
</style>
